package com.wise.service.cms.content.setting;

import com.wise.entities.content.Setting;
import com.wise.framework.daomodel.DaoOne4Update;
import com.wise.framework.daomodel.DaoSave;
import com.wise.framework.session.CurrentUserId;
import com.wise.summer.v1.cms.adminuser.rolemenu.UpdateRoleMenu;

import com.wise.summer.v1.cms.content.setting.AddSetting;
import com.wise.summer.v1.cms.content.setting.UpdateSetting;
import com.wise.summer.v1.cms.content.settings.ListSettings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author futao
 * Created on 2019-06-19.
 */
@Slf4j
@Service
@SummerService
public class UpdateSettingService implements SummerServiceBean<UpdateSetting> {

    private static final String MENU_SOURCE_NAME = "menus";

    @Override
    public void sum(UpdateSetting model) {
        Setting jsonInfo;
        List<Setting> infoList = ListSettings.s(model.getName());
        //不存在就新增
        if (infoList.size() == 0) {
            AddSetting addSetting = new AddSetting();
            addSetting.setInfo(model.getInfo());
            addSetting.setName(model.getName());
            jsonInfo = addSetting.sum();
        } else {
            //存在就更新
            String currentUserId = CurrentUserId.s(true);
            Timestamp currentTimestamp = new Timestamp(DateTime.now().getMillis());
            Setting toUpdate = infoList.get(0);
            jsonInfo = DaoOne4Update.s(Setting.class, toUpdate.getId(), null);
            jsonInfo.setInfo(model.getInfo());
            jsonInfo.setLastUpdateDate(currentTimestamp);
            jsonInfo.setLastUpdateBy(currentUserId);
            DaoSave.s(jsonInfo);
            //如果修改的是系统菜单，则所有的角色菜单要同步修改
            switch (StringUtils.trimToEmpty(model.getName())) {
                //菜单
                case UpdateSettingService.MENU_SOURCE_NAME: {
                    UpdateRoleMenu roleMenu = new UpdateRoleMenu();
                    roleMenu.setMenuInfo(model.getInfo());
                    roleMenu.sum();
                    break;
                }
                default:
                    break;
            }
        }
        model.setSummerResult(jsonInfo);
    }
}
